<template>
  <view class="verification-detail-page">
    <!-- 核销状态 -->
    <view class="verification-status-section">
      <view class="status-icon" :class="getStatusClass(verificationDetail.status)">
        <uni-icons 
          :type="getStatusIcon(verificationDetail.status)" 
          :size="40" 
          :color="getStatusIconColor(verificationDetail.status)"
        ></uni-icons>
      </view>
      <text class="status-text" :class="getStatusClass(verificationDetail.status)">
        {{ getStatusText(verificationDetail.status) }}
      </text>
      <text class="status-desc">{{ getStatusDescription(verificationDetail.status) }}</text>
    </view>

    <!-- 核销信息 -->
    <view class="verification-info-section" v-if="verificationDetail.status === 'completed'">
      <view class="section-title">核销信息</view>
      <view class="info-item">
        <text class="label">核销单号：</text>
        <text class="value">{{ verificationDetail.verificationId }}</text>
      </view>
      <view class="info-item">
        <text class="label">核销时间：</text>
        <text class="value">{{ verificationDetail.verificationTime }}</text>
      </view>
      <view class="info-item">
        <text class="label">核销人员：</text>
        <text class="value">{{ verificationDetail.verifier }}</text>
      </view>
    </view>

    <!-- 订单信息 -->
    <view class="order-info-section">
      <view class="section-title">订单信息</view>
      <view class="info-item">
        <text class="label">订单号：</text>
        <text class="value">{{ verificationDetail.orderId }}</text>
      </view>
      <view class="info-item">
        <text class="label">下单时间：</text>
        <text class="value">{{ verificationDetail.bookingTime }}</text>
      </view>
      <view class="info-item">
        <text class="label">预约日期：</text>
        <text class="value">{{ appointmentDate }}</text>
      </view>
      <view class="info-item">
        <text class="label">预约时间：</text>
        <text class="value">{{ appointmentTime }}</text>
      </view>
    </view>

    <!-- 商品信息 -->
    <view class="product-section">
      <view class="section-title">商品信息</view>
      <view class="product-item">
        <view class="product-details">
          <text class="product-name">{{ verificationDetail.productName }}</text>
          <view class="product-meta">
            <text class="price">¥{{ verificationDetail.price }}</text>
            <text class="quantity">x{{ verificationDetail.quantity }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 费用明细 -->
    <view class="cost-section">
      <view class="section-title">费用明细</view>
      <view class="cost-item">
        <text class="label">商品总额</text>
        <text class="value">¥{{ verificationDetail.price * verificationDetail.quantity }}</text>
      </view>
      <view class="cost-item">
        <text class="label">优惠券</text>
        <text class="value">-¥0</text>
      </view>
      <view class="cost-item total">
        <text class="label">合计</text>
        <text class="value total-price">¥{{ verificationDetail.totalPrice }}</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { getOrderDetails } from '@/services/order.js';
import { formatDateTimeRange } from '@/utils/date.js';


// 导入图标组件
import uniIcons from '@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue';

// 分离预约日期和时间
const appointmentDate = computed(() => {
  if (!verificationDetail.value.useTime) return '';
  
  // 提取日期部分（格式: YYYY-MM-DD）
  const dateMatch = verificationDetail.value.useTime.match(/^\d{4}-\d{2}-\d{2}/);
  return dateMatch ? dateMatch[0] : verificationDetail.value.useTime;
});

// 分离预约时间部分
const appointmentTime = computed(() => {
  if (!verificationDetail.value.useTime) return '';
  
  // 提取时间部分（格式: HH:mm-HH:mm 或包含星期的部分）
  const timeMatch = verificationDetail.value.useTime.match(/\d{4}-\d{2}-\d{2}[\s\S]*?(.*)/);
  if (timeMatch && timeMatch[1]) {
    return timeMatch[1].trim();
  }
  
  // 如果没有匹配到，尝试提取包含时间的部分
  const parts = verificationDetail.value.useTime.split(' ');
  if (parts.length > 1) {
    return parts.slice(1).join(' ');
  }
  
  return verificationDetail.value.useTime;
});

// 核销详情数据
const verificationDetail = ref({
  verificationId: '',
  orderId: '',
  status: 'completed', // 默认状态为已核销
  statusText: '已核销',
  productName: '',
  bookingTime: '',
  useTime: '',
  verificationTime: '',
  verifier: '管理员',
  price: 0,
  quantity: 0,
  totalPrice: 0
});

// 状态枚举映射（与我的订单页面保持一致）
const STATUS_MAP = {
  ALL: 0, // 全部订单
  PENDING: 1, // 待支付
  CANCELLED: 5, // 已取消
  PAID: 10, // 待核销
  PARTIAL_REFUND: 15, // 部分退费
  REFUNDED: 20, // 已退款
  COMPLETED: 25 // 已核销
};

// 获取状态文本（与我的订单页面保持一致）
const getStatusText = (status) => {
  // 如果status是字符串类型，则先映射为数字状态码
  if (typeof status === 'string') {
    const stringToNumberMap = {
      'pending': 1,      // 待支付
      'cancelled': 5,    // 已取消
      'paid': 10,        // 待核销(已支付)
      'partial_refund': 15, // 部分退费
      'refunded': 20,    // 已退款
      'completed': 25    // 已核销
    };
    status = stringToNumberMap[status] || status;
  }
  
  const statusMap = {
    1: '待支付',
    5: '已取消',
    10: '待核销',
    15: '部分退费',
    20: '已退款',
    25: '已核销'
  };
  return statusMap[status] || '未知状态';
};

// 获取状态样式类（与我的订单页面保持一致）
const getStatusClass = (status) => {
  // 如果status是字符串类型，则先映射为数字状态码
  if (typeof status === 'string') {
    const stringToNumberMap = {
      'pending': 1,      // 待支付
      'cancelled': 5,    // 已取消
      'paid': 10,        // 待核销(已支付)
      'partial_refund': 15, // 部分退费
      'refunded': 20,    // 已退款
      'completed': 25    // 已核销
    };
    status = stringToNumberMap[status] || status;
  }
  
  const statusClassMap = {
    1: 'status-pending',
    5: 'status-cancelled',
    10: 'status-paid',
    15: 'status-partial-refund',
    20: 'status-refunded',
    25: 'status-completed'
  };
  return statusClassMap[status] || 'status-completed'; // 默认为已完成状态
};

// 获取订单状态图标
const getStatusIcon = (status) => {
  switch (status) {
    case 'pending':
      return 'circle';
    case 'paid':
      return 'checkbox';
    case 'completed':
      return 'checkmarkempty';
    case 'refunded':
    case 'cancelled':
      return 'closeempty';
    default:
      return 'checkmarkempty';
  }
};

// 获取订单状态图标颜色
const getStatusIconColor = (status) => {
  switch (status) {
    case 'pending':
      return '#fa6f15';
    case 'paid':
      return '#1890ff';
    case 'completed':
      return '#2ab363';
    case 'refunded':
    case 'cancelled':
      return '#999';
    default:
      return '#2ab363';
  }
};

// 获取订单状态描述
const getStatusDescription = (status) => {
  switch (status) {
    case 'pending':
      return '请尽快完成支付';
    case 'paid':
      return '等待使用';
    case 'completed':
      return '订单已核销，服务已完成';
    case 'refunded':
      return '订单已退款';
    case 'cancelled':
      return '订单已取消';
    default:
      return '订单已核销，服务已完成';
  }
};

// 根据状态生成订单状态显示文本
const generateOrderStatus = (status) => {
  switch (status) {
    case 'pending':
      return '待支付';
    case 'paid':
      return '已支付';
    case 'completed':
      return '待核销';
    case 'cancelled':
      return '取消支付';
    case 'refunded':
      return '已退款';
    default:
      return '未知状态';
  }
};

// 获取订单详情并填充核销信息
const fetchOrderDetails = async (orderNo) => {
  try {
    uni.showLoading({
      title: '加载中...'
    });
    
    const response = await getOrderDetails(orderNo);
    
    if (response.code === 200 && response.data) {
      const orderData = response.data;
      
      // 处理预约时间
      let useTime = '';
      try {
        if (orderData.dateTimeRangeList && orderData.dateTimeRangeList.length > 0) {
          const { formattedDate, formattedTimeSlot } = formatDateTimeRange(orderData.dateTimeRangeList);
          useTime = `${formattedDate} ${formattedTimeSlot}`;
        } else if (orderData.priceDateTimeRangeVOList && Array.isArray(orderData.priceDateTimeRangeVOList) && orderData.priceDateTimeRangeVOList.length > 0) {
          // 从 priceDateTimeRangeVOList 中提取预约时间
          const startTime = orderData.priceDateTimeRangeVOList[0].startTime;
          if (startTime) {
            // 格式化 startTime，假设格式为 "YYYY-MM-DD HH:mm:ss"
            const datePart = startTime.split(' ')[0];
            const timePart = startTime.split(' ')[1]?.substring(0, 5); // 提取 HH:mm
            
            // 获取星期几
            const dateObj = new Date(datePart);
            const weekdayMap = {
              0: '周日',
              1: '周一',
              2: '周二',
              3: '周三',
              4: '周四',
              5: '周五',
              6: '周六'
            };
            const weekday = weekdayMap[dateObj.getDay()];
            
            // 如果有多个时间段，显示所有时间段
            if (orderData.priceDateTimeRangeVOList.length > 1) {
              const timeSlots = orderData.priceDateTimeRangeVOList.map(item => {
                return item.startTime.split(' ')[1]?.substring(0, 5) + '-' + item.endTime.split(' ')[1]?.substring(0, 5);
              }).join(', ');
              useTime = `${datePart} (${weekday}) ${timeSlots}`;
            } else {
              // 单个时间段
              const endTime = orderData.priceDateTimeRangeVOList[0].endTime?.split(' ')[1]?.substring(0, 5);
              useTime = `${datePart} (${weekday}) ${timePart}-${endTime}`;
            }
          }
        } else {
          // 如果没有 dateTimeRangeList，尝试其他字段
          useTime = orderData.useTime || orderData.appointmentTime || orderData.useDate || orderData.date || '';
        }
      } catch (error) {
        console.error('格式化预约时间失败:', error);
        useTime = orderData.useTime || orderData.appointmentTime || orderData.useDate || orderData.date || '';
      }
      
      // 根据订单状态设置显示信息
      let status = orderData.status || STATUS_MAP.COMPLETED;
      let statusText = '';
      let verificationId = '';
      let verificationTime = '';
      
      // 将订单状态映射为我的订单页面使用的状态值
      switch (status) {
        case 'pending':
          status = 1;
          statusText = getStatusText(1);
          break;
        case 'paid':
          status = 10;
          statusText = getStatusText(10);
          break;
        case 'completed':
          status = 25;
          statusText = getStatusText(25);
          verificationId = 'VF' + orderData.orderNo?.substring(2); // 基于订单号生成核销单号
          verificationTime = new Date().toLocaleString('zh-CN', { 
            year: 'numeric', 
            month: '2-digit', 
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
          }).replace(/\//g, '-');
          break;
        case 'cancelled':
          status = 5;
          statusText = getStatusText(5);
          break;
        case 'refunded':
          status = 20;
          statusText = getStatusText(20);
          break;
        default:
          // 默认处理
          if (typeof status === 'number') {
            // 如果已经是数字状态码，直接使用
            statusText = getStatusText(status);
          } else {
            // 否则默认为已完成状态
            status = 25;
            statusText = getStatusText(25);
          }
          verificationId = 'VF' + orderData.orderNo?.substring(2);
          verificationTime = new Date().toLocaleString('zh-CN', { 
            year: 'numeric', 
            month: '2-digit', 
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
          }).replace(/\//g, '-');
      }
      
      // 填充核销详情数据
      verificationDetail.value = {
        verificationId: verificationId,
        orderId: orderData.orderNo,
        status: status,
        statusText: statusText,
        productName: orderData.productName || orderData.name || '乒乓球场地预约',
        bookingTime: orderData.createTime || orderData.createTimeStr || '', // 下单时间
        useTime: useTime,
        verificationTime: verificationTime,
        verifier: '管理员',
        price: orderData.orderPayPrice || orderData.totalAmount && orderData.dateTimeRangeList?.length ? 
               (orderData.totalAmount / orderData.dateTimeRangeList.length).toFixed(2) : 
               orderData.price || orderData.totalAmount || 0,
        quantity: orderData.dateTimeRangeList?.length || orderData.quantity || 0,
        totalPrice: orderData.orderPayPrice || orderData.totalAmount || orderData.price || 0
      };
    } else {
      uni.showToast({
        title: response.message || '获取订单详情失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取订单详情失败:', error);
    uni.showToast({
      title: '网络异常，请重试',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};

// 页面加载时初始化
onLoad((options) => {
  // 检查不同的参数名称
  const orderNo = options?.orderNo || options?.orderId || options?.id;
  
  if (orderNo) {
    fetchOrderDetails(orderNo);
  } else {
    uni.showToast({
      title: '缺少订单信息',
      icon: 'none',
      duration: 1500
    });
    
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  }
});
</script>

<style lang="scss" scoped>
.verification-detail-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding: 20rpx;
  padding-bottom: 40rpx;
}

.verification-status-section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 60rpx 30rpx;
  text-align: center;
  margin-bottom: 20rpx;
  
  .status-icon {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 20rpx;
    
    &.status-pending {
      background-color: #ffeee0;
    }
    
    &.status-paid {
      background-color: #e8f4ff;
    }
    
    &.status-completed {
      background-color: #e8fff0;
    }
    
    &.status-refunded {
      background-color: #f0f0f0;
    }
  }
  
  .status-text {
    font-size: 36rpx;
    font-weight: bold;
    margin-bottom: 10rpx;
    
    &.status-pending {
      color: #fa6f15;
    }
    
    &.status-paid {
      color: #1890ff;
    }
    
    &.status-completed {
      color: #2ab363;
    }
    
    &.status-refunded {
      color: #999;
    }
  }
  
  .status-desc {
    font-size: 28rpx;
    color: #999;
  }
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  padding: 10rpx 0;
}

.verification-info-section,
.order-info-section,
.product-section,
.cost-section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 15rpx 0;
  
  .label {
    font-size: 28rpx;
    color: #666;
  }
  
  .value {
    font-size: 28rpx;
    color: #333;
  }
}

.product-item {
  display: flex;
  align-items: center;
  
  .product-image {
    width: 160rpx;
    height: 160rpx;
    border-radius: 12rpx;
    margin-right: 20rpx;
  }
  
  .product-details {
    flex: 1;
    
    .product-name {
      font-size: 30rpx;
      color: #333;
      display: block;
      margin-bottom: 10rpx;
    }
    
    .product-meta {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .price {
        font-size: 32rpx;
        color: #e60012;
        font-weight: bold;
      }
      
      .quantity {
        font-size: 28rpx;
        color: #999;
      }
    }
  }
}

.cost-item {
  display: flex;
  justify-content: space-between;
  padding: 15rpx 0;
  
  .label {
    font-size: 28rpx;
    color: #666;
  }
  
  .value {
    font-size: 28rpx;
    color: #333;
  }
  
  &.total {
    border-top: 1rpx solid #f0f0f0;
    margin-top: 10rpx;
    padding-top: 20rpx;
    
    .value.total-price {
      font-size: 36rpx;
      color: #e60012;
      font-weight: bold;
    }
  }
}
</style>